package com.hdl.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.hdl.entity.HdlUser;
import com.hdl.service.UserService;
import com.hdl.service.impl.UserServiceImpl;
import com.hdl.util.CookieUtil;

/**
 * loginFilter 自动登录过滤器
 */
@WebFilter("/*")
public class loginFilter implements Filter {

    
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		
		UserService service = new UserServiceImpl();
		
		//转型
		HttpServletRequest request = (HttpServletRequest) req;
		
		//判断session中是否有用户数据  是否登陆过
		HdlUser user = (HdlUser) request.getSession().getAttribute("user");
		if(user == null) {//没有登陆过
			//查看cookie中是存有数据    是否选择过自动登录
			Cookie cookie = CookieUtil.getCookie(request.getCookies(), "auto_login");
			if(cookie != null) {//选择了自动登录
				//获取账号密码
				String username = cookie.getValue().split("#")[0];
				String password = cookie.getValue().split("#")[1];
				//在过滤器中实现一次登陆操作
				HdlUser login_user = new HdlUser();
				login_user.setHdlUserName(username);
				login_user.setHdlUserPsd(password);
				//调用方法
				HdlUser login = service.login(login_user);
				//将用户存入session中
				request.getSession().setAttribute("user", login);
				//自动跳转到首页
				request.getRequestDispatcher("/index.jsp").forward(request, resp);
			}
		}
		chain.doFilter(request, resp);//放行
		
	}

	

}
